package com.foling.system.controller.mall;
import com.foling.system.common.Result;
import com.foling.system.entity.User;
import com.foling.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    UserService userService;
    //验证能否成功登录
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestParam("loginName") String loginName,
                        @RequestParam("password") String password,
                        HttpSession httpSession) {
        if (StringUtils.isEmpty(loginName)) {
            return new Result(500,"用户名为空");
        }
        if (StringUtils.isEmpty(password)) {
            return new Result(500,"密码为空");
        }
        List<User> list = userService.list();
        for (User user:list
             ) {
            if (user.getUserName() == Integer.parseInt(loginName) && user.getPassWord() == Integer.parseInt(password)){
                httpSession.setAttribute("User",user);
                return new Result(200,"登陆成功");
            }
        }
        return new Result(500,"账号密码错误");
    }
    //注册
    @PostMapping("/register")
    @ResponseBody
    public Result register(@RequestParam("loginName") String loginName,
                           @RequestParam("password") String password) {
        //500表示错误,200表示正确
        if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(password)) {
            return new Result(500,"用户名或密码为空");
        }
        //是否已经注册
        List<User> users = userService.list();
        for (User user: users
        ) {
            if (Integer.parseInt(loginName) == user.getUserName()){
                return new Result(500,"已注册");
            }
        }
        User user  = new User();
        user.setUserName(Integer.valueOf(loginName));
        user.setUserId(Integer.valueOf(loginName));
        user.setPassWord(Integer.valueOf(password));
        user.setAddress("##");
        userService.save(user);
        return new Result(200,"注册成功");
    }
}
